package Twitim::TrayIcon;

use strict;
use warnings;
use utf8;

use Gtk2;
use Glib qw(TRUE FALSE);
use Twitim::Twitim;
use Twitim::L10N;

sub new {
    my $this  = shift;
    my $mainwin  = shift;
    my $class = ref($this) || $this;
    my $self  = {@_};
    bless $self, $class;

    $self->_start($mainwin);
    return $self;
}

sub is_embedded {
    my $self = shift;
    return $self->{'statusicon'}->is_embedded;
}

sub _start {
    my ( $self, $mainwin ) = @_;

    $self->{'statusicon'}
        = $main::APP_ICON
        ? Gtk2::StatusIcon->new_from_file($main::APP_ICON)
        : Gtk2::StatusIcon->new_from_stock('gtk-missing-image');

    my $screen = $self->{'statusicon'}->get_screen;
    $self->{'statusicon'}->set_screen($screen);
    # $self->{'statusicon'}->set_tooltip("$main::APP_NAME");

    # $self->{'statusicon'}->set_blinking (1);
    # $self->{'statusicon'}->set_visible (1);

    # $self->{'statusicon'}
    #     ->signal_connect( 'activate', sub { $mainwin->hide_show_window } );
    $self->{'statusicon'}->signal_connect( 'popup-menu',
        sub { _popup_menu( @_, $mainwin ); } );
}

sub _popup_menu {
    my ( $icon, $button, $activate_time, $mainwin ) = @_;
    my $menu = Gtk2::Menu->new();

    my $item_view = Gtk2::CheckMenuItem->new( l10n('_Show Twitim') );
    $item_view->set_active( $mainwin->{'top_visible'} );
    $item_view->signal_connect(
        toggled => sub { $mainwin->hide_show_window; } );
    $menu->append($item_view);

    my $item_page = Gtk2::MenuItem->new( l10n('_Open Twitter Web site') );
    $item_page->signal_connect(
        activate => sub { open_url( $main::TWITTER_URL . 'home' ); } );
    $menu->append($item_page);

    my $item_sep1 = Gtk2::SeparatorMenuItem->new;
    $menu->append($item_sep1);

    my $item_prefs
        = Gtk2::ImageMenuItem->new_from_stock( 'gtk-preferences', undef );
    $item_prefs->signal_connect(
        activate => sub { $mainwin->_call_preferences } );
    $menu->append($item_prefs);

    my $item_sep2 = Gtk2::SeparatorMenuItem->new;
    $menu->append($item_sep2);

    my $item_quit = Gtk2::ImageMenuItem->new_from_stock( 'gtk-quit', undef );
    $item_quit->signal_connect( activate => sub { $mainwin->quit } );
    $menu->append($item_quit);

    $menu->show_all;
    $menu->popup( undef, undef,
        sub { $menu->Gtk2::StatusIcon::position_menu($icon); },
        undef, $button, $activate_time );
    undef $menu;    # avoid bothersome segmentation fault

    return TRUE;
}

1;
